package com.drd.dt.modular.service.impl;

import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayFundTransToaccountTransferRequest;
import com.alipay.api.response.AlipayFundTransToaccountTransferResponse;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.drd.dt.back.dto.JGPushDTO;
import com.drd.dt.back.dto.MessageCenterDTO;
import com.drd.dt.common.Constant;
import com.drd.dt.common.SuccessResultEnum;
import com.drd.dt.common.tips.Tip;
import com.drd.dt.exception.BizExceptionEnum;
import com.drd.dt.exception.BussinessException;
import com.drd.dt.modular.dao.MessageMapper;
import com.drd.dt.modular.dao.TradeMapper;
import com.drd.dt.modular.dto.TXListDTO;
import com.drd.dt.modular.dto.TXSuggestDTO;
import com.drd.dt.modular.dto.TradeDTO;
import com.drd.dt.modular.entity.TX;
import com.drd.dt.modular.service.TradeService;
import com.drd.dt.util.JedisClient;
import com.drd.dt.util.JgPushUtil;
import com.drd.dt.util.ResultUtil;
import com.drd.dt.util.StringUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by 86514 on 2019/3/25.
 */
@Service
public class TradeServiceImpl extends ServiceImpl<TradeMapper, TX> implements TradeService {

    String gateway = "https://openapi.alipay.com/gateway.do";
    String app_id = "2019061165492954";
    String private_key = "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCTIChyISaWvtXc9dVKFcxaLQ6oNm06yE3FjdfjsaieIpkc2/FTR7WQb4TluVcQ5bgOXeR9RdvON8ti+pqx4cSQCnLnOeG2JBrX3gsra7IVmrB4QrmhrVXzzpZr184MI81HfK3/K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q+nI5YPEHRT5uycyycooT3k9FwKBgBhdJwBQXBkoSxs7Py8Y4pT05cR3pl9C8hASA09WtRkNJcpDdl1tui+3sdSjE5Z7UgFNC2knqMFIZ2zFjKz/7f352uGjxNJxw/s0DyrGin8ss83lu2NQ7MdwAD9i/Pdtz7kvtRd9IFkpFH0c+0ohBDV1w5+ma8glNzMI4mhWil1BAoGAYdNIiFuWsXiRbpBQ14afLGCaURLgWJdmmmLMDU5QgbSMSUZD1znK0OBlMQyUMB9Nww5TYoLO1qtA0rxhXOCtI+p1tGet6Q9QBPc42fm1zjmorPoikbw/P+hhDd2zcwaQ8a42/SDNBp7akcEzWzSN0u/S+L5/TE2hAeYKh0mEp+A=";
    String charset = "UTF-8";
    String alipay_public_key = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAqOkABsWIfwYPoWVEGUEsv1iyJwHjqDfIbzhO6n90Fqkvhkw3zIVhkcnYr7iO0fH9aTmz9+OFkIQ3Q694KRDQQHADysB5LfFlYNgJbSrULYbioRPPaT3FdY8wxmaSa31GChOdCiNph9OQGQHoY6Pc6lIZayG4Lni2hV5b8smCMVsvT5hX1klPLeTa4tWpL4oVcKVw83san82cPUL0ONbK8KhPlQ/SpYbGqPMLuZKt/5VmkHfi6u1b2YIH49Dcv1WkjqSKlgGCj2dXc2lXzbMUO5PGVnq/zuOcYf3A38YemzyqPBjnbgBqeeXRVNQ9k8wDkP1GJKPP3S6wq1koweLR+wIDAQAB";
    String sign_type = "RSA2";
    String encryptKey = "RGjvbHcphXkFd9SGlBUvRA==";
    @Autowired
    private UserMoneyServiceImpl moneyService;
    @Autowired
    private TradeMapper tradeMapper;
    @Autowired
    private MessageMapper messageMapper;
    @Autowired
    private JedisClient jedisClient;

    /**
     * 我的提现列表
     *
     * @return
     */
    @Override
    public Tip tx(Integer user_id, String token, Integer pageNum, String type) throws Exception {
        if (StringUtils.isEmpty(user_id) || StringUtils.isEmpty(token)) {
            throw new BussinessException(BizExceptionEnum.PARAM_EMPTY);
        }
        if (StringUtils.isEmpty(type) || type.equals("0")) {
            type = "";
        }
        Integer pageSize = Constant.PAGE_SIZE_20;
        Page page = new Page(pageNum, pageSize);
        List<TXListDTO> result = tradeMapper.getTxList(page, type, user_id);
        page.setRecords(result);
        return ResultUtil.result(SuccessResultEnum.SUCCESS.getCode(), SuccessResultEnum.SUCCESS.getMessage(), page);
    }

    /**
     * 创建提现申请
     */
    @Override
    public Tip addTx(TXSuggestDTO txSuggestDTO) throws Exception {
        Integer user_id = txSuggestDTO.getUser_id();
        String token = txSuggestDTO.getToken_id();
        //提现类型(1普通佣金  2奖励金  3活动佣金)
        Integer type = txSuggestDTO.getType();
        if (StringUtils.isEmpty(user_id) || StringUtils.isEmpty(token) || StringUtils.isEmpty(type)) {
            throw new BussinessException(BizExceptionEnum.PARAM_EMPTY);
        }
        //从redeis获取用户提现记录
        String str = jedisClient.get("htsq:trade:" + user_id + "_" + type);
        Date date = new Date();
        if (!StringUtils.isEmpty(str)) {
            TXSuggestDTO trade = JSON.parseObject(str, TXSuggestDTO.class);
            String time = trade.getTime();
            SimpleDateFormat y_m_d = Constant.y_M_d;
            Date tx_date = y_m_d.parse(time);
            Date now = y_m_d.parse(y_m_d.format(date));
            if (tx_date.getTime() == now.getTime() || tx_date.getTime() > now.getTime()) {
                return ResultUtil.result(607, "每天最多能提现1次");
            }
        }

        //查询用户金额
        Map userMap = tradeMapper.findUserBalance(user_id);
        String userRmb = "0.0";
        if (null != userMap) {
            if (type == 1) {//普通
                userRmb = String.valueOf(userMap.get("normal_balance"));
            } else if (type == 2) {//奖励金
                userRmb = String.valueOf(userMap.get("bounty_balance"));
            } else if (type == 3) {//活动佣金
                userRmb = String.valueOf(userMap.get("activity_balance"));
            }
        }
        //获取提现配置信息
        TradeDTO configInfo = tradeMapper.selectConfigInfo(user_id, type);
        Double withdraw_min_amount = configInfo.getWithdraw_min_amount();
        Integer today_withdraw_num = configInfo.getCount();//用户今天已提现次数
        Integer withdraw_num_per_day = configInfo.getWithdraw_num_per_day();
        Integer balance_status = configInfo.getBalance_status();//资产冻结 0表示未冻结 1表示资金被冻结
        Double less_than_autopay = configInfo.getLess_than_autopay();//多少元自动转账
        Integer withdraw_auto_to_alipay = configInfo.getWithdraw_auto_to_alipay();//提现自动转支付宝

        Double money = Double.valueOf(txSuggestDTO.getMoney());//提现金额

        if (null != withdraw_min_amount && money < withdraw_min_amount) {
            return ResultUtil.result(607, "最少提现" + withdraw_min_amount + "元", userRmb);
        }
        //每天提现次数规则
        if (null != withdraw_num_per_day && today_withdraw_num >= withdraw_num_per_day) {
            return ResultUtil.result(607, "每天最多能提现" + withdraw_num_per_day + "次");
        }
        if (balance_status == 1) {
            throw new BussinessException(BizExceptionEnum.TX_STATUS_ERROR);
        }
        Double surplus = Double.valueOf(userRmb) - money;
        if (surplus >= 0) {
            //保存用户提现记录到redis
            txSuggestDTO.setTime(Constant.y_M_d_H_m_s.format(date));
            jedisClient.setWithExpire("htsq:trade:" + user_id + "_" + type, JSON.toJSONString(txSuggestDTO), 60 * 60 * 24);//保存24小时
            //允许提现
            String orderid = String.valueOf(System.currentTimeMillis()) + user_id;
            //1. 创建提现记录
            Double fee = 0.0;//手续费
            Double final_money = money - fee;//实际到账金额
            TX tx = new TX();
            BeanUtils.copyProperties(txSuggestDTO, tx);
            tx.setCreate_time(Constant.y_M_d_H_m_s.format(new Date()));
            tx.setTxid(String.valueOf(orderid));
            tx.setStatus(0);
            tx.setFee(String.valueOf(fee));
            tx.setFinal_money(String.valueOf(final_money));
            Integer txIsSuccess = tradeMapper.insert(tx);
            Integer id = tx.getId();

            moneyService.txUpdate(user_id, 1, money, type);//修改余额和balance详情
            if (txIsSuccess == 1) {
                //当申请的钱在正常打款范围和开户了自动打款功能，则调用支付宝转账接口
                if (money < less_than_autopay && withdraw_auto_to_alipay == 1) {
                    String alipay_user_name = txSuggestDTO.getAlipay_name();
                    String alipay_account = txSuggestDTO.getAlipay_account();
                    if (AliPay(String.valueOf(orderid), alipay_user_name, String.valueOf(final_money), alipay_account)) {
                        tx = new TX();
                        tx.setId(id);
                        tx.setStatus(1);
                        tradeMapper.updateById(tx);//自动转账成功
                        //新增提现消息中心的消息
                        MessageCenterDTO messageCenterDTO = new MessageCenterDTO();
                        messageCenterDTO.setStatus(1);
                        messageCenterDTO.setTitle(Constant.TX_WITHDRAW_TITLE);
                        messageCenterDTO.setContent(Constant.TX_SUCCESS);
                        messageCenterDTO.setHead_pic(Constant.DEFAULT_HEAD_PIC);
                        messageCenterDTO.setMoney(money);
                        messageCenterDTO.setUser_id(user_id);
                        messageCenterDTO.setCreate_time(Constant.y_M_d_H_m_s.format(new Date()));
                        messageCenterDTO.setTx_id(id);
                        messageMapper.insertTxMessage(messageCenterDTO);
                        //获取极光key，secret和用户的极光id
                        Map<String, String> jg = tradeMapper.getJgInfoAndUser(user_id);
                        //将提现信息通过极光推送给用户
                        if (null != jg) {
                            String user_jp_id = jg.get("jp_id");
                            String deviceT = String.valueOf(jg.get("deviceT"));//客户端类型（Android:0  IOS:1）
                            String masterSecret = jg.get("jg_app_secret");
                            String appKey = jg.get("jg_app_key");
                            //ios使用券巴士的极光
                            String ios_appKey = Constant.QBS_JG_APPKEY;
                            String ios_masterSecret = Constant.QBS_JG_APPSECRET;
                            if (!StringUtils.isEmpty(user_jp_id) && !StringUtils.isEmpty(deviceT)) {
                                Integer dev = Integer.valueOf(deviceT);//客户端类型（Android:0  IOS:1）
                                JGPushDTO dto = new JGPushDTO();
                                dto.setJump_action(2);
                                dto.setIs_login(1);
                                if (dev == 0) {
                                    JgPushUtil.pushMsg(Constant.TX_SUCCESS, dto, appKey, masterSecret, user_jp_id);
                                } else if (dev == 1) {
                                    JgPushUtil.pushMsg(Constant.TX_SUCCESS, dto, ios_appKey, ios_masterSecret, user_jp_id);
                                }
                            }
                        }
                    }
                }
            }
            return ResultUtil.result(SuccessResultEnum.TRADE_SUCCESS.getCode(), SuccessResultEnum.TRADE_SUCCESS.getMessage(), String.format("%.2f", surplus));
        } else {
            throw new BussinessException(BizExceptionEnum.USER_MONEY_NOTENOUGHT);
        }
    }

    /**
     * 阿里转账
     *
     * @param orderid
     * @param payee_real_name
     * @param price
     * @param payee_account
     * @return
     */
    public boolean AliPay(String orderid, String payee_real_name, String price, String payee_account) {
        try {
            AlipayClient alipayClient = new DefaultAlipayClient(gateway, app_id, private_key, "json", charset, alipay_public_key, sign_type);
            ((DefaultAlipayClient) alipayClient).setEncryptKey(encryptKey);
            AlipayFundTransToaccountTransferRequest requestali = new AlipayFundTransToaccountTransferRequest();
            String context = getPayContent(orderid, payee_real_name, price, payee_account);
            requestali.setBizContent(context);
            AlipayFundTransToaccountTransferResponse responseali = alipayClient.execute(requestali);
            if (responseali.isSuccess()) {
                return true;
            } else {
                return false;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * @param orderid         订单ID
     * @param payee_real_name 支付宝姓名
     * @param price           提现金额
     * @param payee_account   支付宝账号
     * @return
     */
    private String getPayContent(String orderid, String payee_real_name, String price, String payee_account) {


        String result = "{" +
                "    \"out_biz_no\":\"" +
                orderid +
                "\"," +
                "    \"payee_type\":\"ALIPAY_LOGONID\"," +
                "    \"payee_account\":\"" +
                payee_account +
                "\"," +
                "    \"amount\":\"" +
                price +
                "\"," +
                "    \"payer_show_name\":\"核桃省钱\"," +
                "    \"payee_real_name\":\"" +
                payee_real_name +
                "\"," +
                "    \"remark\":\"核桃省钱提现\"," +
                "  }";
        return result;

    }
}
